<?php

namespace Mouta\UserBundle\Security\User\Provider;

use Mouta\AmistateBundle\Entity\SocialNetwork;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use \BaseFacebook;
use \FacebookApiException;

class FacebookProvider implements UserProviderInterface
{
    /**
     * @var \Facebook
     */
    protected $facebook;
    protected $userManager;
    protected $validator;

    public function __construct(BaseFacebook $facebook, $userManager, $validator)
    {
        $this->facebook = $facebook;
        $this->userManager = $userManager;
        $this->validator = $validator;
    }

    public function supportsClass($class)
    {
        return $this->userManager->supportsClass($class);
    }

    public function loadUserByUsername($username)
    {
		$user = null;
        try {
            $this->facebook->setExtendedAccessToken();
            $fbdata = $this->facebook->api('/me');
        } catch (FacebookApiException $e) {
            $fbdata = null;
        }

        if (!empty($fbdata)) {
            if(isset($fbdata['email']))
            {
                $user = $this->userManager->findUserBy(array('email' => $fbdata['email']));
            }
            else
            {
                $user = $this->userManager->findUserBy(array('fb_id' => $fbdata['id']));
            }

            if (empty($user)) {
                $user = $this->userManager->createUser();
                $user->setEnabled(true);
                $user->setPlainPassword(substr(md5(uniqid()), 0, 8));

                // TODO use http://developers.facebook.com/docs/api/realtime
                $user->setFBData($fbdata);

                if (count($this->validator->validate($user, 'Facebook'))) {
                    // TODO: the user was found obviously, but doesnt match our expectations, do something smart
                    throw new UsernameNotFoundException('The facebook user could not be stored');
                }
                $this->userManager->updateUser($user);
            } else {
                if (isset($fbdata['id']) && $fbdata['id'] != $user->getFbId())
                {
                    $user->setFbId($fbdata['id']);
                    $user->setFacebook( 'http://www.facebook.com/profile.php?id=' . $fbdata['id']);
                    $this->userManager->updateUser($user);
                }
            }

            $socialFacebook = new SocialNetwork();
            foreach($user->getSocialNetwork() as $social)
            {
                if($social->getTipo() == 1)
                {
                    $socialFacebook = $social;
                }
            }
            $socialFacebook->setTipo(1);
            $socialFacebook->setUsuario($user);
            $socialFacebook->setSecret("");
            $socialFacebook->setToken($this->facebook->getAccessToken());
            $socialFacebook->setUrl(isset($fbdata['link'])?$fbdata['link']:'');
            $socialFacebook->setExternalId($fbdata['id']);

            $user->addSocialNetwork($socialFacebook);

            $this->userManager->updateUser($user);

        }

        if (empty($user)) {
            throw new UsernameNotFoundException('The user is not authenticated on facebook');
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user)) || !$user->getFbId()) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }

        return $this->loadUserByUsername($user->getFbId());
    }
}